package com.example.rumen;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class student extends AppCompatActivity {

    private SQLiteDatabase database;
    private EditText bianhao;
    private EditText name;
    private EditText age;
    private EditText czbianhao;
    private EditText czname;
    private TextView czresult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_student);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        bianhao = findViewById(R.id.bianhao);
        name = findViewById(R.id.name);
        age = findViewById(R.id.age);

        czbianhao = findViewById(R.id.czbianhao);
        czname = findViewById(R.id.czxingming);
        czresult = findViewById(R.id.result);

        Mydatabase mydatabase = new Mydatabase(getApplicationContext());
        database = mydatabase.getWritableDatabase();

    }

    /**
     * 实现增加数据
     *
     * @param view
     */
    public void insert(View view) {


     /*
       //发方法一
       String sql1 = "select * from user where 编号 = ?";
        Cursor cursor = database.rawQuery(sql1, new String[]{bianhao.getText().toString()});
        if (cursor.getCount() == 0) {
            String sql = "insert into user(编号,姓名,年龄) values(?,?,?)";
            database.execSQL(sql, new Object[]{Integer.parseInt(bianhao.getText().toString()), name.getText().toString(), Integer.parseInt(age.getText().toString())});
            Toast.makeText(getApplicationContext(), "增加成功", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getApplicationContext(), "编号已存在", Toast.LENGTH_SHORT).show();
        }


        */


        String sql1 = "select * from user where 编号 = ?";
        Cursor cursor = database.rawQuery(sql1, new String[]{bianhao.getText().toString()});
        if (cursor.getCount() == 0) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("编号", Integer.parseInt(bianhao.getText().toString()));
            contentValues.put("姓名", name.getText().toString());
            contentValues.put("年龄", Integer.parseInt(age.getText().toString()));
            database.insert("user", null, contentValues);

            Toast.makeText(getApplicationContext(), "增加成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "编号已存在", Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 根据编号删除数据
     *
     * @param view
     */
    public void delete(View view) {
        String bianhaoStr = bianhao.getText().toString();
        if (bianhaoStr.isEmpty()) {
            Toast.makeText(getApplicationContext(), "请输入要删除的编号", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            int bianhaoInt = Integer.parseInt(bianhaoStr);
            String sql = "delete from user where 编号 = ?";
            database.execSQL(sql, new Object[]{bianhaoInt});
            Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
        } catch (NumberFormatException e) {
            Toast.makeText(getApplicationContext(), "编号格式错误", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "删除失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 更新数据
     *
     * @param view
     */
    public void update(View view) {
      /*  String bianhaoStr = bianhao.getText().toString();
        String nameStr = name.getText().toString();
        String ageStr = age.getText().toString();

        if (bianhaoStr.isEmpty()) {
            Toast.makeText(getApplicationContext(), "请输入要更新的编号", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            int bianhaoInt = Integer.parseInt(bianhaoStr);
            int ageInt = ageStr.isEmpty() ? 0 : Integer.parseInt(ageStr);

            StringBuilder sqlBuilder = new StringBuilder("update user set ");
            boolean hasUpdate = false;

            if (!nameStr.isEmpty()) {
                sqlBuilder.append("姓名 = ?");
                hasUpdate = true;
            }

            if (!ageStr.isEmpty()) {
                if (hasUpdate) {
                    sqlBuilder.append(", ");
                }
                sqlBuilder.append("年龄 = ?");
                hasUpdate = true;
            }

            if (!hasUpdate) {
                Toast.makeText(getApplicationContext(), "请输入需要更新的姓名或年龄", Toast.LENGTH_SHORT).show();
                return;
            }

            sqlBuilder.append(" where 编号 = ?");
            String sql = sqlBuilder.toString();

            Object[] params;
            if (!nameStr.isEmpty() && !ageStr.isEmpty()) {
                params = new Object[]{nameStr, ageInt, bianhaoInt};
            } else if (!nameStr.isEmpty()) {
                params = new Object[]{nameStr, bianhaoInt};
            } else {
                params = new Object[]{ageInt, bianhaoInt};
            }

            database.execSQL(sql, params);
            Toast.makeText(getApplicationContext(), "更新成功", Toast.LENGTH_SHORT).show();
        } catch (NumberFormatException e) {
            Toast.makeText(getApplicationContext(), "编号或年龄格式错误", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "更新失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }*/


        String sql = "update user set 姓名=?,年龄=? where 编号=?";
        database.execSQL(sql,new Object[]{name.getText().toString(),
                Integer.parseInt(age.getText().toString()),Integer.parseInt(bianhao.getText().toString())});
        Toast.makeText(getApplicationContext(), "更新成功", Toast.LENGTH_SHORT).show();

    }


    /**
     * 根据编号查找数据
     *
     * @param view
     */
    @SuppressLint("Range")
    public void bhchazhao(View view) {
        String bianhaoStr = czbianhao.getText().toString();

        if (bianhaoStr.isEmpty()) {
            Toast.makeText(getApplicationContext(), "请输入要查找的编号", Toast.LENGTH_SHORT).show();
            return;
        }

        String sql = "select * from user where 编号=?";
        Cursor cursor = database.rawQuery(sql, new String[]{bianhaoStr});

        if (cursor.moveToFirst()) {  // Changed from while to if
            int find_bianhao = cursor.getInt(cursor.getColumnIndex("编号"));
            String find_name = cursor.getString(cursor.getColumnIndex("姓名"));
            int find_age = cursor.getInt(cursor.getColumnIndex("年龄"));

            AlertDialog.Builder builder = new AlertDialog.Builder(student.this);
            builder.setIcon(R.drawable.hana);
            builder.setTitle("温馨提示");
            builder.setMessage("您当前查找的编号"+find_bianhao+",姓名为"+find_name+",年龄为"+find_age);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    czresult.setText("编号:"+find_bianhao+"\n姓名:"+find_name+"\n年龄:"+find_age);
                }
            });

            builder.setNegativeButton("NONO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    czresult.setText("未找到相关数据");
                }
            });

            builder.show();
        } else {
            Toast.makeText(getApplicationContext(), "未找到该编号", Toast.LENGTH_SHORT).show();
        }

        cursor.close(); // Don't forget to close the cursor
    }

    /**
     * 根据姓名查找数据（可能有多个结果）
     * 普通版，和老师的逻辑差不多
     * @param view
     */
/*    @SuppressLint("Range")
    public void czname(View view) {
        String nameStr = czname.getText().toString();

        if (nameStr.isEmpty()) {
            Toast.makeText(getApplicationContext(), "请输入要查找的姓名", Toast.LENGTH_SHORT).show();
            return;
        }

        String sql = "select * from user where 姓名 like ?";
        Cursor cursor = database.rawQuery(sql, new String[]{"%" + nameStr + "%"});


        while (cursor.moveToNext()) {
            int find_bianhao = cursor.getInt(cursor.getColumnIndex("编号"));
            String find_name = cursor.getString(cursor.getColumnIndex("姓名"));
            int find_age = cursor.getInt(cursor.getColumnIndex("年龄"));

            AlertDialog.Builder builder = new AlertDialog.Builder(student.this);
            builder.setIcon(R.drawable.hana);
            builder.setTitle("温馨提示");
            builder.setMessage("您当前查找的编号"+find_bianhao+",姓名为"+find_name+",年龄为"+find_age);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    czresult.setText("编号:"+find_bianhao+"\n姓名:"+find_name+"\n年龄:"+find_age);
                }
            });
            builder.setNegativeButton("NONO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    czresult.setText("未找到相关数据");
                }
            });
            builder.show();
        }

    }*/

    /**
     * 不能滑动版
     * @param view
     */
    /*@SuppressLint("Range")
    public void czname(View view) {
        String nameStr = czname.getText().toString();

        if (nameStr.isEmpty()) {
            Toast.makeText(getApplicationContext(), "请输入要查找的姓名", Toast.LENGTH_SHORT).show();
            return;
        }

        String sql = "select * from user where 姓名 like ?";
        Cursor cursor = database.rawQuery(sql, new String[]{"%" + nameStr + "%"});

        StringBuilder result = new StringBuilder();
        int count = 0;

        // 收集所有匹配的记录
        if (cursor.moveToFirst()) {
            do {
                count++;
                int find_bianhao = cursor.getInt(cursor.getColumnIndex("编号"));
                String find_name = cursor.getString(cursor.getColumnIndex("姓名"));
                int find_age = cursor.getInt(cursor.getColumnIndex("年龄"));

                // 将每条记录添加到结果字符串中
                result.append("记录 ").append(count).append(":\n");
                result.append("编号: ").append(find_bianhao).append("\n");
                result.append("姓名: ").append(find_name).append("\n");
                result.append("年龄: ").append(find_age).append("\n\n");

            } while (cursor.moveToNext());

            // 一次性显示一个包含所有记录的对话框
            final String finalResult = result.toString();
            AlertDialog.Builder builder = new AlertDialog.Builder(student.this);
            builder.setIcon(R.drawable.hana);
            builder.setTitle("温馨提示");
            builder.setMessage("共找到 " + count + " 条记录:\n\n" + finalResult);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 在TextView中一次性显示所有记录
                    czresult.setText(finalResult);
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.show();
        } else {
            Toast.makeText(getApplicationContext(), "未找到包含 \"" + nameStr + "\" 的姓名", Toast.LENGTH_SHORT).show();
        }

        cursor.close();
    }
*/
    /**
     * 滑动查看版
     * @param view
     */
    @SuppressLint("Range")
    public void czname(View view) {
        String nameStr = czname.getText().toString();

        if (nameStr.isEmpty()) {
            Toast.makeText(getApplicationContext(), "请输入要查找的姓名", Toast.LENGTH_SHORT).show();
            return;
        }

        String sql = "select * from user where 姓名 like ?";
        Cursor cursor = database.rawQuery(sql, new String[]{"%" + nameStr + "%"});

        StringBuilder result = new StringBuilder();
        int count = 0;

        // 收集所有匹配的记录
        if (cursor.moveToFirst()) {
            do {
                count++;
                int find_bianhao = cursor.getInt(cursor.getColumnIndex("编号"));
                String find_name = cursor.getString(cursor.getColumnIndex("姓名"));
                int find_age = cursor.getInt(cursor.getColumnIndex("年龄"));

                // 将每条记录添加到结果字符串中
                result.append("记录 ").append(count).append(":\n");
                result.append("编号: ").append(find_bianhao).append("\n");
                result.append("姓名: ").append(find_name).append("\n");
                result.append("年龄: ").append(find_age).append("\n\n");

            } while (cursor.moveToNext());

            // 一次性显示一个包含所有记录的对话框
            final String finalResult = result.toString();
            AlertDialog.Builder builder = new AlertDialog.Builder(student.this);
            builder.setIcon(R.drawable.hana);
            builder.setTitle("温馨提示");
            builder.setMessage("共找到 " + count + " 条记录:\n\n" + finalResult);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 在TextView中一次性显示所有记录
                    czresult.setText(finalResult);

                    // 设置TextView为可滚动
                    czresult.setMovementMethod(new ScrollingMovementMethod());

                    // 确保TextView可以获取焦点，以便滚动
                    czresult.setFocusable(true);
                    czresult.setFocusableInTouchMode(true);
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.show();
        } else {
            Toast.makeText(getApplicationContext(), "未找到包含 \"" + nameStr + "\" 的姓名", Toast.LENGTH_SHORT).show();
        }

        cursor.close(); // 不要忘记关闭游标
    }
}